// bin2c.c：将文件转换为C语言二进制数组
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
    if (argc != 4) {
        fprintf(stderr, "用法：%s <输入文件> <输出C文件> <数组名>\n", argv[0]);
        return 1;
    }

    FILE* in = fopen(argv[1], "rb");
    FILE* out = fopen(argv[2], "w");
    if (!in || !out) {
        perror("文件操作失败");
        return 1;
    }

    // 获取文件大小
    fseek(in, 0, SEEK_END);
    long size = ftell(in);
    fseek(in, 0, SEEK_SET);

    // 写入C数组头
    fprintf(out, "const unsigned char %s[] = {\n", argv[3]);
    fprintf(out, "    ");

    // 读取文件并转换为十六进制
    unsigned char buf[1];
    int count = 0;
    while (fread(buf, 1, 1, in) > 0) {
        fprintf(out, "0x%02X, ", buf[0]);
        if (++count % 16 == 0) { // 每16个字节换行，格式美观
            fprintf(out, "\n    ");
        }
    }

    // 写入数组尾
    fprintf(out, "\n};\n");
    fprintf(out, "const unsigned int %s_size = %ld;\n", argv[3], size);

    fclose(in);
    fclose(out);
    printf("成功生成C数组：%s（大小：%ld字节）\n", argv[2], size);
    return 0;
}